<template>
  <el-dialog title="配置角色"
  :model-value="modelValue"
  @close="closed"
  >
    <el-checkbox-group v-model="userRoleTitleList">
      <el-checkbox v-for="item in allRoleList" :key="item.id" :label="item.name">
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="closed">取消</el-button>
      <el-button type="primary" @click="onComfirm">确认</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue'
import { roleList } from '../../../../api/role'
import { updateRole, userRole } from '../../../../api/user'
import { watchSwitchLang } from '../../../../utils/i18n'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  userId: {
    type: String,
    required: true
  }
})
const emits = defineEmits(['update:modelValue', 'updateRole'])
// const i18n = useI18n()
const onComfirm = async () => {
  const roles = userRoleTitleList.value.map(name => {
    return allRoleList.value.find(role => role.name === name)
  })
  await updateRole(props.userId, roles)
  // 角色更新成功!
  emits('updateRole')
  closed()
}
const closed = () => {
  emits('update:modelValue', false)
}
// 所有角色
const allRoleList = ref([])
const getListData = async () => {
  allRoleList.value = await roleList()
}
getListData()
watchSwitchLang(getListData())
// 当前用户角色
const userRoleTitleList = ref([])
const getUserRoles = async () => {
  const res = await userRole(props.userId)
  userRoleTitleList.value = res.sysRoles.map(item => item.name)
}
watch(() => props.userId, value => {
  if (value) getUserRoles()
})
</script>
<style lang="scss" scoped></style>
